package com.ruoyi.wvp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.enums.DeletedEnum;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.wvp.domain.DataRole;
import com.ruoyi.wvp.domain.DataRoleAddressUnit;
import com.ruoyi.wvp.mapper.DataRoleAddressUnitMapper;
import com.ruoyi.wvp.mapper.DataRoleMapper;
import com.ruoyi.wvp.service.IDataRoleAddressUnitService;
import com.ruoyi.wvp.service.IDataRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 部门数据权限Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-08-11
 */
@Service
@Slf4j
public class DataRoleAddressUnitServiceImpl extends ServiceImpl<DataRoleAddressUnitMapper,DataRoleAddressUnit> implements IDataRoleAddressUnitService {



        @Override
        public List<DataRoleAddressUnit> listAll(DataRoleAddressUnit dataRole) {
            return list(getQueryWrapper(dataRole));
        }

    @Override
    public void addAll(DataRole dataRole) {
        List<Long> addressUnitIds = dataRole.getAddressUnitIds();
        removeAllAddressUnit(dataRole.getId());
        ArrayList<DataRoleAddressUnit> saveList = new ArrayList<>(addressUnitIds.size());
        addressUnitIds.forEach(addressUnitId -> {
            DataRoleAddressUnit roleAddressUnit = new DataRoleAddressUnit();
            roleAddressUnit.setAddressUnitId(addressUnitId);
            roleAddressUnit.setDataRoleId(dataRole.getId());
            saveList.add(roleAddressUnit);
        });
        saveBatch(saveList);
    }

    public void removeAllAddressUnit(Long dataRoleId) {
        DataRoleAddressUnit dataRoleAddressUnit = new DataRoleAddressUnit();
        dataRoleAddressUnit.setDataRoleId(dataRoleId);
        remove(getQueryWrapper(dataRoleAddressUnit));
    }

    private  LambdaQueryWrapper<DataRoleAddressUnit> getQueryWrapper(DataRoleAddressUnit dataRole) {
            LambdaQueryWrapper<DataRoleAddressUnit> queryWrapper = Wrappers.lambdaQuery(DataRoleAddressUnit.class);
            if(Objects.nonNull(dataRole.getDataRoleId())){
                queryWrapper.eq(DataRoleAddressUnit::getDataRoleId,dataRole.getDataRoleId());
            }
            return queryWrapper;
        }

}
